var tuiwa = require("../../tuiwa.js");
Page({
  data: {
    value: '',
    filePath: '',
    // is_true: 1,
  },
  onLoad: function (query) {
    var that = this
    this.setData({
      value: query.value,
      filePath: query.images,
      is_true: query.is_true,
      width: query.width,
      height: query.height,
      top: query.top,
      left: query.left,
      num: query.num,
    });
    //获取用户设备信息，屏幕宽度
    tt.getSystemInfo({
      success: res => {
        // console.log(res, 'getSystemInfo')
        that.setData({
          screenWidth: res.screenWidth,
          screenHeight: res.screenHeight,
          pixelRatio: res.pixelRatio,
        })
        // console.log(that.data.pixelRatio, that.data.screenWidth, that.data.screenHeight)
      }
    })
    tt.getImageInfo({
      src: that.data.filePath,
      success: function (res) {
        that.setData({
          shareImgSrc: res.path,
          shareWidth: res.width,
          shareHeight: res.height,
        });
        // console.log("getImageInfo", that.data.shareImgSrc, that.data.shareWidth, that.data.shareHeight)
      }
    })
    tuiwa.globalData.currentPage = this
    // console.log(this.data.width, this.data.height, this.data.left, this.data.top, this.data.num, this.data.filePath, this.data.is_true)
  },
  //获取临时路径
  getTempFilePath: function () {
    var that = this
    // console.log('111')
    tt.canvasToTempFilePath({
      canvasId: 'share',
      destWidth: that.data.screenWidth * that.data.pixelRatio,
      destHeight: that.data.screenHeight * that.data.pixelRatio,
      success: (res) => {
        // console.log(res)
        that.setData({
          shareTempFilePath: res.tempFilePath
        })
        tt.saveImageToPhotosAlbum({
          filePath: that.data.shareTempFilePath,
          success: (res) => {
            // console.log(res)
            tt.showToast({ title: "成功保存到本地相册" });
            // that.setData({
            //   canvasHidden: true
            // })
          },
          fail: (err) => {
            console.log(err)
          }
        })
      },
      fail: (err) => {
        console.log(err)
      }
    })
  },
  save() {
    tuiwa.auth();
    // console.log(this.data.is_true)
    var _this = this
    if (_this.data.is_true != 1) {
      // console.log(this.data.is_true)
      tt.showModal({
        title: '温馨提示',
        content: '点击确定前往观看视频',
        cancelText: '取消',
        success(res) {
          if (res.confirm) {
            // console.log('用户点击确定');
            tuiwa.playAd();
          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        }
      });
    } else {
      // console.log(this.data.is_true)
      //绘制
      let shareImgSrc = this.data.shareImgSrc
      let shareWidth = this.data.shareWidth
      let shareHeight = this.data.shareHeight
      let value = this.data.value
      let screenWidth = this.data.screenWidth
      let screenHeight = this.data.screenHeight
      let textWidth = 0.01 * (this.data.left) * screenWidth
      let textHeight = 0.01 * (this.data.top) * screenHeight
      // console.log(shareImgSrc, screenWidth, screenHeight, textWidth, textHeight)
      var context = tt.createCanvasContext('share')
      context.drawImage(shareImgSrc, 0, 0, screenWidth, screenHeight)
      context.setFontSize(15)
      // context.setTextAlign('center')
      context.setFillStyle(this.data.num)
      // context.fillText(value, 135 + textWidth, textHeight)
      drawText(context, value, 135 + textWidth, textHeight, 16, 132) // 自动换行
      context.draw(true, this.getTempFilePath)
      // console.log(135 + textWidth, textHeight)
      // 将文字绘制到行 长文本自动换行 并返回行数
      /*
      * params
      * @context        createCanvasContext定义的属性名
      * @text           需要绘制的文本字符
      * @startX         第一行文本的起始X坐标
      * @startY         第一行文本的起始Y坐标
      * @lineHeight     文本行高
      * @MAX_WIDTH      单行文字最大宽度，超过临界值自动换行
      *
      * return rowLength  返回绘制文本的行数
      * */
      function drawText(context, text, startX, startY, lineHeight, MAX_WIDTH) {
        let allAtr = text.split('');
        let rowArr = []; // 拆分出来的每一行
        let rowStrArr = []; // 每一行的文字数组
        for (let i = 0; i < allAtr.length; i++) {
          const currentStr = allAtr[i];
          rowStrArr.push(currentStr);
          const rowStr = rowStrArr.join('');
          if (context.measureText(rowStr).width > MAX_WIDTH) {
            rowStrArr.pop(); // 删除最后一个
            rowArr.push(rowStrArr.join('')); // 完成一行
            rowStrArr = [currentStr];
            continue;
          }
          // 最后一个字母 直接添加到一行
          if (i === allAtr.length - 1) {
            rowArr.push(rowStr); // 完成一行
          }
        }
        for (let i = 0; i < rowArr.length; i++) {
          context.fillText(rowArr[i], startX, startY + i * lineHeight);
        }
        return rowArr.length;
      }
    }
  },
  onShow: function () {
    // this.util();
    var _this = this
    setTimeout(function () {
      _this.getHeight();
    }, 100)
  },
  util: function (obj) {
    // console.log(obj, -obj.list, obj.container);
    var continueTime = (parseInt(obj.list / obj.container) + 1) * 5000;
    var setIntervalTime = 50 + continueTime;
    var animation = tt.createAnimation({
      duration: 200,  // 动画时长
      timingFunction: "linear", // 线性
      delay: 10  // 0则不延迟
    });
    this.animation = animation;
    animation.translateY(obj.container)
      .step({ duration: 50, timingFunction: 'step-start' })
      .translateY(-obj.list)
      .step({ duration: continueTime });
    this.setData({
      animationData: animation.export()
    })
    setInterval(() => {
      animation.translateY(obj.container)
        .step({ duration: 50, timingFunction: 'step-start' })
        .translateY(-obj.list)
        .step({ duration: continueTime });
      this.setData({
        animationData: animation.export()
      })
    }, setIntervalTime)
  },
  getHeight() {
    var obj = new Object();
    //创建节点选择器
    var query = tt.createSelectorQuery();
    query.select('.container').boundingClientRect()
    query.select('.list').boundingClientRect()
    query.exec((res) => {
      obj.container = res[0].height; // 框的height
      obj.list = res[1].height; // list的height
      // return obj;
      this.util(obj);
    })
  },
  // 预览图片
  preview: function () {
    tt.navigateTo({ // 含动画效果
      url: '../../pages/getCard/getCard?value=' + this.data.value
        + '&images=' + this.data.filePath
        + '&is_true=' + this.data.is_true
        + '&left=' + this.data.left
        + '&width=' + this.data.width
        + '&height=' + this.data.height
        + '&top=' + this.data.top
        + '&num=' + this.data.num,
    });
  },
  closeAdFunction: function () {
    // console.log("看完了");
    this.setData({
      is_true: 1
    })
    tt.downloadFile({
      url: this.data.filePath,
      header: {
        "content-type": "application/json",
      },
      success: (res) => {
        //绘制
        let shareImgSrc = this.data.shareImgSrc
        let shareWidth = this.data.shareWidth
        let shareHeight = this.data.shareHeight
        let value = this.data.value
        let screenWidth = this.data.screenWidth
        let screenHeight = this.data.screenHeight
        let textWidth = 0.01 * (this.data.left) * screenWidth
        let textHeight = 0.01 * (this.data.top) * screenHeight
        // console.log(shareImgSrc, screenWidth, screenHeight, textWidth, textHeight)
        var context = tt.createCanvasContext('share')
        context.drawImage(shareImgSrc, 0, 0, screenWidth, screenHeight)
        context.setFontSize(15)
        // context.setTextAlign('center')
        context.setFillStyle(this.data.num)
        drawText(context, value, 135 + textWidth, textHeight, 16, 132) // 自动换行
        context.draw(true, this.getTempFilePath)
        // console.log(135 + textWidth, textHeight)
        // 将文字绘制到行 长文本自动换行 并返回行数
        /*
        * params
        * @context        createCanvasContext定义的属性名
        * @text           需要绘制的文本字符
        * @startX         第一行文本的起始X坐标
        * @startY         第一行文本的起始Y坐标
        * @lineHeight     文本行高
        * @MAX_WIDTH      单行文字最大宽度，超过临界值自动换行
        *
        * return rowLength  返回绘制文本的行数
        * */
        function drawText(context, text, startX, startY, lineHeight, MAX_WIDTH) {
          let allAtr = text.split('');
          let rowArr = []; // 拆分出来的每一行
          let rowStrArr = []; // 每一行的文字数组
          for (let i = 0; i < allAtr.length; i++) {
            const currentStr = allAtr[i];
            rowStrArr.push(currentStr);
            const rowStr = rowStrArr.join('');
            if (context.measureText(rowStr).width > MAX_WIDTH) {
              rowStrArr.pop(); // 删除最后一个
              rowArr.push(rowStrArr.join('')); // 完成一行
              rowStrArr = [currentStr];
              continue;
            }
            // 最后一个字母 直接添加到一行
            if (i === allAtr.length - 1) {
              rowArr.push(rowStr); // 完成一行
            }
          }
          for (let i = 0; i < rowArr.length; i++) {
            context.fillText(rowArr[i], startX, startY + i * lineHeight);
          }
          return rowArr.length;
        }
      },
      fail: (err) => {
        tt.showModal({
          title: "下载出错",
          content: err.errMsg,
          showCancel: false,
        });
      },
    });
    // tuiwa.getAdEvent("videoEnd")
  },
  cancelAdFunction: function () {
    // console.log("没看完广告");
    tt.showModal({
      title: "温馨提示",
      content: "要观看完整视频才能进入哦~",
      showCancel: !1
    })
  },
  //
  back: function () {
    this.setData({
      is_true: 1
    })
    tt.navigateBack({
      delta: 2
    });
  },
  toBack() {
    wx.navigateBack({
      delta: 1
    })
  },
})
